<template>
    <div>
      <div class="target-element" ref="targetElement" style="width: 200px; height: 200px; background-color: #ccc;">
        Target Element
      </div>
      <button @click="captureAndConvert">Capture and Convert</button>
      <div>
        <img :src="capturedImage" alt="Captured Image" v-if="capturedImage" />
      </div>
    </div>
 </template>
  <script setup lang="ts">
import { ref } from "vue";
  
  const targetElement = ref<HTMLDivElement | null>(null);
  const capturedImage = ref<string | null>(null);
  
  const captureAndConvert = () => {
    if (!targetElement.value) return;
  
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
  
    if (!ctx) return;
  
    // 设置 canvas 尺寸与目标元素相同
    canvas.width = targetElement.value.offsetWidth;
    canvas.height = targetElement.value.offsetHeight;
  
    // 将目标元素绘制到 canvas 中
    ctx.drawImage(targetElement.value, 0, 0, targetElement.value.offsetWidth, targetElement.value.offsetHeight);
  
    // 将图像数据转换为 Base64 格式的字符串
    const base64String = canvas.toDataURL('image/png');
  
    // 更新 capturedImage
    capturedImage.value = base64String;
  };

</script>
 
  
  <style scoped>
  .target-element {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  </style>
  